package com.system.borrow.activity;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.R;
import com.system.borrow.bean.GloData;
import com.system.borrow.bean.Province;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.fragment.FastFragment;
import com.system.borrow.fragment.HomeFragment;
import com.system.borrow.fragment.MyFragment;
import com.system.borrow.fragment.SearchFragment;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.SystemBarTintManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 主页
 */
public class HomeActivity extends BaseActivity implements View.OnClickListener{
    public TextView tv_sy,tv_ks,tv_ss,tv_my;
    HomeFragment homeFragment;
    FastFragment fastFragment;
    SearchFragment searchFragment;
    MyFragment myFragment;
    FrameLayout ly_content;
    SystemBarTintManager tintManager;
    public static HomeActivity homeActivity;
    private  List<Province> list = new ArrayList<Province>();
    TextView tv_unread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        homeActivity = this;
        tintManager = new SystemBarTintManager(this);
        initView();
        loadData();
        initListener();
    }

    private void loadData() {
        OkHttpUtils.get(URLDefind.ADDRESS)
                .tag(this)
                .execute(new DialogCallback<String>(this, String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray("data");
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {
                                TypeToken<Province> token = new TypeToken<Province>() {
                                };
                                Province province = gson.fromJson(array.getString(i),token.getType());
                                list.add(province);
                            }
                            GloData.setList(list);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }

    /**
     * 设置监听
     */
    private void initListener() {
        tv_sy.setOnClickListener(this);
        tv_ks.setOnClickListener(this);
        tv_ss.setOnClickListener(this);
        tv_my.setOnClickListener(this);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        tv_sy.setSelected(true);
        homeFragment = new HomeFragment();
        fastFragment = new FastFragment();
        searchFragment = new SearchFragment();
        myFragment = new MyFragment();
        transaction.add(R.id.fragment_container, fastFragment);
        transaction.add(R.id.fragment_container, searchFragment);
        transaction.add(R.id.fragment_container, myFragment);
        hideAllFragment(transaction);
        transaction.add(R.id.fragment_container, homeFragment);
        transaction.show(homeFragment);
        transaction.commit();
//        initWindowView();
    }

    private void initView() {
        tv_sy = (TextView) findViewById(R.id.tv_sy);
        tv_ks = (TextView) findViewById(R.id.tv_ks);
        tv_ss = (TextView) findViewById(R.id.tv_ss);
        tv_my = (TextView) findViewById(R.id.tv_my);
        ly_content = (FrameLayout) findViewById(R.id.fragment_container);
        tv_unread = (TextView) findViewById(R.id.tv_unread);
    }
    public void updataUnread(){
        tv_unread.setText(GloData.getNum()+"");
        if(GloData.getNum()==0){
            tv_unread.setVisibility(View.GONE);
            if(MyFragment.myFragment!=null){
                MyFragment.myFragment.setUnRead(false);
            }
        }else{
            tv_unread.setVisibility(View.VISIBLE);
            if(MyFragment.myFragment!=null){
                MyFragment.myFragment.setUnRead(true);
            }
        }
    }
    //重置所有文本的选中状态
    public void selected() {
        tv_ks.setSelected(false);
        tv_my.setSelected(false);
        tv_ss.setSelected(false);
        tv_sy.setSelected(false);
    }

    @Override
    public void onClick(View view) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        switch (view.getId()) {
            case R.id.tv_sy:
//                initWindowView();
                selected();
                tv_sy.setSelected(true);
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.fragment_container, homeFragment);
                } else {
                    transaction.show(homeFragment);
                }
                transaction.commit();
                break;
            case R.id.tv_ks:
//                initWindowRes();
                selected();
                tv_ks.setSelected(true);
                if (fastFragment == null) {
                    fastFragment = new FastFragment();
                    transaction.add(R.id.fragment_container, fastFragment);
                } else {
                    transaction.show(fastFragment);
                }
                transaction.commit();
                break;
            case R.id.tv_ss:
//                initWindowRes();
                selected();
                tv_ss.setSelected(true);
                if (searchFragment == null) {
                    searchFragment = new SearchFragment();
                    transaction.add(R.id.fragment_container, searchFragment);
                } else {
                    transaction.show(searchFragment);
                }
                transaction.commit();
                break;
            case R.id.tv_my:
//                Intent intent = new Intent(this,LoginActivity.class);
//                startActivity(intent);
//                initWindowRes();
                if (GloData.getCustomerDTO() == null) {
                    Intent loginIntent = new Intent(this, LoginActivity.class);
                    startActivity(loginIntent);
                    return;
                }
                selected();
                tv_my.setSelected(true);
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    transaction.add(R.id.fragment_container, myFragment);
                } else {
                    transaction.show(myFragment);
                }
                transaction.commit();
                break;
        }
    }

    //隐藏所有Fragment
    public void hideAllFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (fastFragment != null) {
            transaction.hide(fastFragment);
        }
        if (searchFragment != null) {
            transaction.hide(searchFragment);
        }
        if (myFragment != null) {
            transaction.hide(myFragment);
        }
    }

    public void initWindowView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(Color.parseColor("#636363"));

            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(attrs);
            ViewGroup contentView = (ViewGroup) findViewById(android.R.id.content);
            contentView.getChildAt(0).setPadding(0, 0, 0, 0);
        }
    }

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public void initWindowRes() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            ViewGroup contentView = (ViewGroup) findViewById(android.R.id.content);
            contentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            int statusHeight = getStatusBarHeight(this);
            contentView.getChildAt(0).setPadding(0, 0, 0, 0);
            contentView.getChildAt(0).setPadding(0, statusHeight, 0, 0);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(R.color.full_transparent);
        }
    }
    public void exitLogin(){
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        selected();
        tv_ss.setSelected(true);
        if(searchFragment==null){
            searchFragment = new SearchFragment();
            transaction.add(R.id.fragment_container,searchFragment);
        }else{
            transaction.show(searchFragment);
        }
        transaction.commitAllowingStateLoss();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long exitTime = 0;

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(),
                    "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            exitApp();
        }
    }

}
